/*
 * MainWindow.java
 *
 * Created on 4. September 2008, 03:00
 */
package clip.gui;

import L.L;
import clip.clipApp;
import clip.model.Buddy;
import clip.model.BuddyList;
import clip.model.Options;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author  admin
 */
public class MainWindow extends javax.swing.JFrame implements Observer, DropTargetListener {
    //NICHT BENUTZEN
    @Deprecated
    public MainWindow() {
        initComponents();
    }
    clipApp app;

    public MainWindow(clipApp a) {
        app = a;


        initComponents();

        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowDeiconified(WindowEvent e) {
                setVisible(true);
                app.trayIcon.setVisible(true);
            }

            @Override
            public void windowIconified(WindowEvent e) {
                setVisible(false);
                app.trayIcon.setVisible(true);
            }

            @Override
            public void windowClosing(WindowEvent e) {
                Options.saveOptionsInstance();
                System.exit(0);
            }
        });

        jList_Buddies.setCellRenderer(new BuddyListCellRenderer());
        app.buddyList.notifyListDataChanged();

        jList_Buddies.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
            }
        });

    //dragndrop test
        ((JComponent) this.getContentPane()).setTransferHandler(new DnDTransferHandler());
    }

    public Buddy getSelectedBuddy() {
        return (Buddy) jList_Buddies.getSelectedValue();
    }

    public void update(Observable o, Object arg) {
        updateStatusLabel(o.getClass().getSimpleName() + " : " + arg.toString());
    }

    public void updateStatusLabel(String message) {
        final String msg = message;
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                jLabel_status.setText(msg);
            }
        });
    }

    public BuddyList getBuddies() {
        return app.buddyList;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu_BuddyList = new javax.swing.JPopupMenu();
        jMenuItem_pullClipboard = new javax.swing.JMenuItem();
        jMenuItem_connect = new javax.swing.JMenuItem();
        jMenuItem_removeBuddy = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItem_addBuddy = new javax.swing.JMenuItem();
        jMenuItem_sendMessage = new javax.swing.JMenuItem();
        jScrollPane_BuddyList = new javax.swing.JScrollPane();
        jList_Buddies = new javax.swing.JList((ListModel) app.buddyList);
        jLabel_status = new javax.swing.JLabel();
        jMenuBar = new javax.swing.JMenuBar();
        jMenu_FileMenu = new javax.swing.JMenu();
        jMenuItem_Quit = new javax.swing.JMenuItem();

        jPopupMenu_BuddyList.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                jPopupMenu_BuddyListPopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                jPopupMenu_BuddyListPopupMenuWillBecomeVisible(evt);
            }
        });

        jMenuItem_pullClipboard.setText("pull Clipboard");
        jMenuItem_pullClipboard.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_pullClipboardActionPerformed(evt);
            }
        });
        jPopupMenu_BuddyList.add(jMenuItem_pullClipboard);

        jMenuItem_connect.setText("connect");
        jMenuItem_connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_connectActionPerformed(evt);
            }
        });
        jPopupMenu_BuddyList.add(jMenuItem_connect);

        jMenuItem_removeBuddy.setText("remove");
        jMenuItem_removeBuddy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_removeBuddyActionPerformed(evt);
            }
        });
        jPopupMenu_BuddyList.add(jMenuItem_removeBuddy);
        jPopupMenu_BuddyList.add(jSeparator1);

        jMenuItem_addBuddy.setText("add new Buddy");
        jMenuItem_addBuddy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_addBuddyActionPerformed(evt);
            }
        });
        jPopupMenu_BuddyList.add(jMenuItem_addBuddy);

        jMenuItem_sendMessage.setText("send Message...");
        jMenuItem_sendMessage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_sendMessageActionPerformed(evt);
            }
        });
        jPopupMenu_BuddyList.add(jMenuItem_sendMessage);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("netclip3000");

        jList_Buddies.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList_Buddies.setComponentPopupMenu(jPopupMenu_BuddyList);
        jList_Buddies.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jList_BuddiesMousePressed(evt);
            }
        });
        jList_Buddies.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jList_BuddiesKeyPressed(evt);
            }
        });
        jScrollPane_BuddyList.setViewportView(jList_Buddies);

        jLabel_status.setText("status?");

        jMenu_FileMenu.setText("File");

        jMenuItem_Quit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem_Quit.setText("Quit");
        jMenuItem_Quit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_QuitActionPerformed(evt);
            }
        });
        jMenu_FileMenu.add(jMenuItem_Quit);

        jMenuBar.add(jMenu_FileMenu);

        setJMenuBar(jMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel_status, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane_BuddyList, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(86, 86, 86)
                .addComponent(jScrollPane_BuddyList, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel_status))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jMenuItem_QuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_QuitActionPerformed
    System.exit(0);
}//GEN-LAST:event_jMenuItem_QuitActionPerformed

private void jPopupMenu_BuddyListPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jPopupMenu_BuddyListPopupMenuWillBecomeInvisible
}//GEN-LAST:event_jPopupMenu_BuddyListPopupMenuWillBecomeInvisible

private void jPopupMenu_BuddyListPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jPopupMenu_BuddyListPopupMenuWillBecomeVisible
    boolean aBuddyIsSelected = getSelectedBuddy() != null;
    jMenuItem_connect.setEnabled(aBuddyIsSelected);
    jMenuItem_pullClipboard.setEnabled(aBuddyIsSelected);
    jMenuItem_removeBuddy.setEnabled(aBuddyIsSelected);
}//GEN-LAST:event_jPopupMenu_BuddyListPopupMenuWillBecomeVisible

private void jMenuItem_pullClipboardActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_pullClipboardActionPerformed
    if (getSelectedBuddy() != null) {
        try {
            app.setSystemClipboard(getSelectedBuddy().getClipboardSnapshot());
        } catch (RemoteException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        //handle
        }
    }
}//GEN-LAST:event_jMenuItem_pullClipboardActionPerformed

private void jMenuItem_connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_connectActionPerformed
    if (getSelectedBuddy() != null) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                getSelectedBuddy().connectToBuddy();
            }
        });
    }
}//GEN-LAST:event_jMenuItem_connectActionPerformed

private void jMenuItem_addBuddyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_addBuddyActionPerformed
    String input = JOptionPane.showInputDialog(this, "enter nickname@host:port", "enter buddy information", JOptionPane.QUESTION_MESSAGE);
    if (input.isEmpty()) {
        return;
    }//GEN-LAST:event_jMenuItem_addBuddyActionPerformed
        int atIndex = input.indexOf("@");
        int doppelpunktIndex = input.indexOf(":");
        if (atIndex < 0 || doppelpunktIndex < 0) {
            return;
        }
        String nick = input.substring(0, atIndex);
        String host = input.substring(atIndex + 1, doppelpunktIndex);
        int port = Integer.parseInt(input.substring(doppelpunktIndex + 1));
        L.o("new buddy nick,host,port", nick, host, port);
        //adden
        app.buddyList.add(new Buddy(nick, host, port));
    }

private void jList_BuddiesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList_BuddiesMousePressed
}//GEN-LAST:event_jList_BuddiesMousePressed

private void jMenuItem_removeBuddyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_removeBuddyActionPerformed
    if (getSelectedBuddy() == null) {
        return;
    }
    app.buddyList.remove(getSelectedBuddy());

}//GEN-LAST:event_jMenuItem_removeBuddyActionPerformed

private void jList_BuddiesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList_BuddiesKeyPressed
    if (getSelectedBuddy() == null) {
        return;
    }
    int key = evt.getKeyCode();
    switch (key) {
        case KeyEvent.VK_DELETE:
            app.buddyList.remove(getSelectedBuddy());
            break;
    }
}//GEN-LAST:event_jList_BuddiesKeyPressed

private void jMenuItem_sendMessageActionPerformed(java.awt.event.ActionEvent evt) {                                                      
    if (getSelectedBuddy()==null) return;
    String message = JOptionPane.showInputDialog(this, "", "message for "+getSelectedBuddy().getNickname(), JOptionPane.PLAIN_MESSAGE);
        try {
            getSelectedBuddy().receiveMessage(message);
        } catch (RemoteException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel_status;
    private javax.swing.JList jList_Buddies;
    private javax.swing.JMenuBar jMenuBar;
    private javax.swing.JMenuItem jMenuItem_Quit;
    private javax.swing.JMenuItem jMenuItem_addBuddy;
    private javax.swing.JMenuItem jMenuItem_connect;
    private javax.swing.JMenuItem jMenuItem_pullClipboard;
    private javax.swing.JMenuItem jMenuItem_removeBuddy;
    private javax.swing.JMenuItem jMenuItem_sendMessage;
    private javax.swing.JMenu jMenu_FileMenu;
    private javax.swing.JPopupMenu jPopupMenu_BuddyList;
    private javax.swing.JScrollPane jScrollPane_BuddyList;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables
    
    
    //DROPTARGETLISTENER
    public void dragEnter(DropTargetDragEvent dtde) {
        L.m();
    }

    public void dragOver(DropTargetDragEvent dtde) {
        L.m();
    }

    public void dropActionChanged(DropTargetDragEvent dtde) {
        L.m();
    }

    public void dragExit(DropTargetEvent dte) {
        L.m();
    }

    public void drop(DropTargetDropEvent evt) {
     try {
            Transferable t = evt.getTransferable();
    
            if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)|| true) {
                evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                List<File> files = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
                evt.getDropTargetContext().dropComplete(true);
                
                //hier abgehn
                L.d("empfange dnd files:"+files.toString());
            } else {
                evt.rejectDrop();
            }
        } catch (IOException e) {
            evt.rejectDrop();
        } catch (UnsupportedFlavorException e) {
            evt.rejectDrop();
        }

    }
}
